<?php

namespace App\Jobs;

use App\Http\Controllers\Home\Orders\Api\OrdersApi;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;

/**
 * @descr   作用:15分钟取消未付款订单,并返回库存
 * @author  liuguansheng
 * Class OrdersQueue
 * @package App\Jobs
 */
class OrdersQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $ordersApi;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(OrdersApi $ordersApi)
    {
        $this->ordersApi = $ordersApi;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        ///查出所有未付款的订单
		$ordersInfo = DB::table('orders')->where('state',0	)->get();
		if ($ordersInfo) {
			foreach ($ordersInfo as &$item) {
				$addTime = strtotime($item->created_at);
				$time = time()-$addTime;
				//将订单未付款时间超过15分钟的都关闭(订单状态改为4--交易关闭)
				if ($time > 10) {
					$id = $item->id;
					DB::table('orders')->where('id',"=","$id")->update(['state'=>4]);
					//查出所有该订单下的商品的gid;
					$detail = DB::table('orders_details')->select(['gprice_id','buy_num'])->where('oid',"=","$id")->get();
//					dd($detail);
					foreach ($detail as &$val) {
						$gid = $val->gprice_id;
						//查询该gid对应goods_price表的商品库存
						$gpInfo = DB::table('goods_price')->select('storage')->where('id','=',"$gid")->get();
						foreach ($gpInfo as $value) {
//							dd($value);
							$storage = $value->storage;
//							dd($val);
							$newSto = $storage + $val->buy_num;
							//将库存返回
							$detail = DB::table('goods_price')->where('id',"=","$gid")->update(['storage'=>$newSto]);
						}
					}
				}
			}
		}

    }
}
